import { cart } from "@mall/api-services"
import * as _ from "lodash"
import { action, computed, observable } from "mobx"

export class Cart {

  @observable
  private items: cart.CartItem[] = []

  @action
  public add(item: cart.CartItem) {
    this.items.push(item)
  }

  @action
  public addAll(items: cart.CartItem[]) {
    for (const item of items) {
      if (!this.contains(item)) {
        this.add(item)
      }
    }
  }

  @action
  public remove(item: cart.CartItem) {
    _.remove(this.items, aItem => aItem.variantId === item.variantId)
  }

  @action
  public removeAll(items: cart.CartItem[]) {
    for (const item of items) {
      this.remove(item)
    }
  }

  public containsAll(items: cart.CartItem[]): boolean {
    const itemIds = _.map(this.items, item => item.variantId)
    const aItemIds = _.map(items, item => item.variantId)
    for (const aItemId of aItemIds) {
      if (!_.includes(itemIds, aItemId)) {
        return false
      }
    }
    return true
  }

  public contains(item: cart.CartItem): boolean {
    const itemIds = _.map(this.items, aItem => aItem.variantId)
    return _.includes(itemIds, item.variantId)
  }

  public getItems() {
    return [...this.items]
  }

  @computed
  public get count() {
    return this.items.length
  }

  @computed
  public get totalAmount(): number {
    return _.reduce(this.items, (amount, item) => amount + item.price, 0)
  }
}
